package com.momoda.monitor.util;

import com.momoda.monitor.bean.FileMetaInfo;
import com.momoda.monitor.config.MonitorFtpFolder;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;

@EnableConfigurationProperties(MonitorFtpFolder.class)
public class FileUtil {


    private static FileUtil fileUtil = new FileUtil();

    private FileUtil() {

    }

    public static FileUtil getFileUtil() {
        return fileUtil;
    }


    public static String info = "info.json";
    public static String FtpRootPath = "D:/SFTP/";

    @Autowired
    MonitorFtpFolder monitorFtpFolder;

    /**
     * 文件如果不存在创建，存在不做操作
     *
     * @param path
     */
    public static File fileCreateIfNotExist(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 生成info配置文件,根据路径生成info配置文件，路径不匹配则在根目录生成
     *
     * @param srcPath
     */
    public File generateInfoFile(String srcPath) {

        //1. 反义字符转换
        srcPath = srcPath.replaceAll("\\\\", "/");

//        absolutePath = absolutePath.replaceFirst("D:/SFTP", "");//去掉开始
//        "path": "D:/SFTP/clients/ThingJS/13687/12345/index.json",
        String decPath = "";
        //2. 根据配置文件生成info文件
        Set<String> pathSets = readProperties();
        for (String path : pathSets) { //parh=D:/SFTP/clients/ThingJS/
            if (srcPath.startsWith(path)) {
                //移除前缀
                String suffix = srcPath.replaceAll(path, "");//   13687/12345/index.json
                if (suffix.contains("/")) {//说明是个目录，存在userid标识的
                    String userid = suffix.substring(0, suffix.indexOf("/"));//   13824
                    decPath = path + userid + File.separator + FileUtil.info;//在配置目录在的userid目录下创建配置文件
                    //    文件如果不存在创建，存在不做操作
                    return FileUtil.fileCreateIfNotExist(decPath);
                } else {
                    return FileUtil.fileCreateIfNotExist(path + FileUtil.info);
                }

            }
        }

        // 3. 如果没有在配置文件定义，则在跟目录生成
        return FileUtil.fileCreateIfNotExist(FileUtil.FtpRootPath + FileUtil.info);
    }


    /**
     * 获取指定监控目录的value
     *
     * @return
     */
    public Set readProperties() {

        Set pathSets = new HashSet();


        Properties properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        InputStream in = FileUtil.class.getClassLoader().getResourceAsStream("config/monitor-ftp-folder.properties");
        // 使用properties对象加载输入流
        try {

            properties.load(in);
            Iterator<Map.Entry<Object, Object>> it = properties.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<Object, Object> entry = it.next();
                String key = (String) entry.getKey();
                if (key.startsWith("ftp.monitor.")) {
                    String value = (String) entry.getValue();
                    pathSets.add(value);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return pathSets;
    }

    /**
     * 读取json文件转成bean对象，
     * 文件不存在创建，
     * json为空，new对象
     *
     * @param infoFile
     * @return
     */
    public static FileMetaInfo readInfoFileToBean(File infoFile) {
        if (!infoFile.exists()) {
            try {
                infoFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String infoStr = null;
        try {
            infoStr = FileUtils.readFileToString(infoFile, Charset.forName("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileMetaInfo metaInfo = (FileMetaInfo) FastJsonUtils.convertJSONToObject(infoStr, FileMetaInfo.class);
        //内容为空，则new
        if (metaInfo == null) {
            metaInfo = new FileMetaInfo();
        }
        return metaInfo;

    }

    public static void writeBeanToInfoFile(File infoFile, FileMetaInfo metaInfo) {
        // 3. 修改并写入json文件

        String json = FastJsonUtils.convertObjectToJSON(metaInfo);
        try {
            FileUtils.write(infoFile, json, Charset.forName("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        InputStream in = FileUtil.class.getClassLoader().getResourceAsStream("config/monitor-ftp-folder.properties");
        // 使用properties对象加载输入流
        properties.load(in);
        //获取key对应的value值
        properties.getProperty("monitor.ThingJS");
        System.out.println(properties.keySet());

        System.out.println(properties.getProperty("monitor.ThingJS"));
        Iterator<Map.Entry<Object, Object>> it = properties.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = it.next();
            String key = (String) entry.getKey();
            if (key.startsWith("monitor.")) {
                String value = (String) entry.getValue();
                System.out.println(value);
            }

        }
    }
}
